package com.zzx.boot.websocket.handler;

import com.google.gson.Gson;
import com.zzx.boot.message.Message;
import com.zzx.boot.serializable.CustomSerializable;
import com.zzx.boot.websocket.session.WebSocketSession;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;

public class GlobalWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {



    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

        String text = textWebSocketFrame.text();
        // 添加
        Message message = CustomSerializable.gson().fromJson(text, Message.class);
        System.out.println("messageReceived");
        channelHandlerContext.fireChannelRead(message);
    }

    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        WebSocketSession.removeSessionByChannel(ctx.channel());
        System.out.println("被断开了");
//        super.close(ctx, promise);
    }
}
